python 解压包含中文路径 文件名的ZIP 您所在的位置:网站首页 python zip解压缩 python 解压包含中文路径 文件名的ZIP

python 解压包含中文路径 文件名的ZIP

2023-08-07 12:38| 来源: 网络整理| 查看: 265

zip解压缩,压缩包里含有中文路径、文件名时由于编码方式的问题而导致报错,通过try:except进行编码测试然后再解压即可,之前看的各种方式。总是在不同环境下各种不同的问题,如py代码编码环境不一样,重写权限问题(有的方式是解压一遍后遍历乱码的解压结果,再重新编码再重新解压,这个会有性能问题),通过下面的方式则不存在性能问题,因为不需要解压两遍。

def zip_decompress(zip_file,path): try: zip_dir=os.path.splitext(os.path.basename(zip_file))[0] zip = zipfile.ZipFile(zip_file, 'r') if not os.path.isdir(path): os.makedirs(path) for each in zip.namelist(): if not each.endswith('/'): root, name = os.path.split(each) try: root = root.encode('cp437').decode('gbk') except: root = root.encode('cp437').decode('utf-8') try: name = name.encode('cp437').decode('gbk') except: name = name.encode('cp437').decode('utf-8') directory = os.path.normpath(os.path.join(path,zip_dir, root)) if not os.path.isdir(directory): os.makedirs(directory) file=open(os.path.join(directory, name), 'wb') file.write(zip.read(each)) file.close() zip.close() except Exception as e: print (str(e))



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有